package com.txtsqlclient.domain;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.txtsqlclient.dataaccess.database.connection.ConnectionException;

/**
 * @author spadda
 * 
 */
public class FileDataSource extends DataSource {

	protected String dirPath;

	private static Log LOGGER = LogFactory.getLog(FileDataSource.class);

	public FileDataSource(final DataSourceType dsType) {
		if (DataSourceFactory.LEGAL_FILE_DATASOURCE_TYPES.contains(dsType)) {
			this.dsType = dsType;
		} else {
			throw new IllegalArgumentException("The given Data Source Type, :"
					+ dsType + " is not a valid File Data Source.");
		}
	}

	public FileDataSource(final DataSourceType dsType, final String dirPath) {
		this(dsType);
		this.dirPath = dirPath;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.txtsqlclient.domain.DataSource#openConnection()
	 */
	@Override
	public Connection openConnection() throws ConnectionException {
		final String url = this.dsType.getConnectionURL(this);
		Connection dbCon = null;
		try {
			dbCon = DriverManager.getConnection(url);
		} catch (SQLException sqle) {
			throw new ConnectionException(
					"Error opening connection to the database:" + this, sqle);
		}
		LOGGER.info("Opened connection to the database");
		return dbCon;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.txtsqlclient.domain.DataSource#readConnectionDetailsFromFile()
	 */
	@Override
	public void readConnectionDetailsFromFile() {
		throw new UnsupportedOperationException();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.txtsqlclient.domain.DataSource#writeConnectionDetailsToFile()
	 */
	@Override
	public void writeConnectionDetailsToFile() {
		throw new UnsupportedOperationException();

	}

	public String formatURL(String urlFormatStr) {
		String urlStr = urlFormatStr.replaceAll("\\{dir\\}", this.dirPath);
		LOGGER.debug("Formatted file access URL is: " + urlStr);
		return urlStr;
	}

	public int hashCode() {
		final int prime = 31;
		int hashCode = 7;
		hashCode = prime * hashCode + this.dsType.hashCode();
		hashCode = prime * hashCode + this.dirPath.hashCode();
		return hashCode;
	}

	public boolean equals(final Object ds) {
		if (ds instanceof FileDataSource) {
			FileDataSource fds = (FileDataSource) ds;
			if (this.dsType.equals(fds.dsType)
					&& this.dirPath.equals(fds.dirPath)) {
				return true;
			}
		}
		return false;
	}

	public String toString() {
		final StringBuffer buf = new StringBuffer();
		buf.append("[DataSourceType:");
		buf.append(this.dsType);
		buf.append(", DirectoryPath:");
		buf.append(this.dirPath);
		buf.append("]");
		return buf.toString();
	}

}
